package com.ruoyi.client.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.ruoyi.client.domain.Address;
import com.ruoyi.client.pojo.form.AddressSaveForm;
import com.ruoyi.client.pojo.vo.AddressVo;
import com.ruoyi.client.service.IAddressService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.bean.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

@Anonymous  //接口允许匿名访问
@RestController
@RequestMapping("/address")
public class AddressController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(AddressController.class);
    @Resource
    private IAddressService addressService;

    //查询登录用户的收货地址列表
    @GetMapping("/list")
    public AjaxResult list(){
        // 当前登录用户,未登录会抛出例外NotLoginException
        Long userId = StpUtil.getLoginIdAsLong();

        List<AddressVo> list = addressService.list(userId);
        return AjaxResult.success(list);
    }

    // 保存/新增收货地址
    @PostMapping("/save")
    public AjaxResult save(@RequestBody @Valid AddressSaveForm form) {
        // 当前登录用户,未登录会抛出例外NotLoginException
        Long userId = StpUtil.getLoginIdAsLong();

        Address address = new Address();
        BeanUtils.copyProperties(form,address);
        address.setUserId(userId); //这步很重要

        if(addressService.save(address)){
            return AjaxResult.success();
        }else{
            return AjaxResult.error();
        }
    }

    // 查询收货地址详情
    @GetMapping("/detail")
    public AjaxResult detail(@RequestParam Long id){
        // 用户登录验证,未登录会抛出例外NotLoginException
        StpUtil.checkLogin();

        AddressVo addressVo = addressService.selectById(id);
        return AjaxResult.success(addressVo);
    }

    // 删除
    @GetMapping("/delete")
    public AjaxResult delete(@RequestParam Long id){
        // 用户登录验证,未登录会抛出例外NotLoginException
        StpUtil.checkLogin();

        if(addressService.delete(id)){
            return AjaxResult.success();
        }else{
            return AjaxResult.error();
        }
    }

    // 获取默认的收货地址,如果传递了id就获取id对应的收货地址，如果没有传递id就获取默认的收货地址(取按默认排序后的首个记录)
    @GetMapping("/default")
    public AjaxResult getDefault(Long id){
        // 当前登录用户,未登录会抛出例外NotLoginException
        Long userId = StpUtil.getLoginIdAsLong();

        AddressVo addressVo = addressService.getDefault(userId,id);
        return AjaxResult.success(addressVo);
    }

}
